<template>
  <div class="host-detail">
    <!-- 基本信息 -->
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <div class="header-actions">
                <el-button @click="connectSSH">
                  <el-icon><Monitor /></el-icon>
                  SSH连接
                </el-button>
                <el-button @click="testConnection">
                  <el-icon><Connection /></el-icon>
                  测试连接
                </el-button>
                <el-button type="primary" @click="handleEdit">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
              </div>
            </div>
          </template>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="主机名">
              {{ host.hostname }}
            </el-descriptions-item>
            <el-descriptions-item label="IP地址">
              {{ host.ip }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(host.status)">
                <el-icon><component :is="getStatusIcon(host.status)" /></el-icon>
                {{ getStatusText(host.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="最后心跳">
              {{ host.last_heartbeat ? formatTime(host.last_heartbeat) : '从未连接' }}
            </el-descriptions-item>
            <el-descriptions-item label="主机类型">
              {{ host.host_type_name }}
            </el-descriptions-item>
            <el-descriptions-item label="环境">
              {{ host.environment_name }}
            </el-descriptions-item>
            <el-descriptions-item label="主机组">
              {{ host.host_group_name || '未分组' }}
            </el-descriptions-item>
            <el-descriptions-item label="负责人">
              {{ host.owner_name || '未指定' }}
            </el-descriptions-item>
            <el-descriptions-item label="操作系统">
              {{ host.os || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="系统版本">
              {{ host.os_version || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="内核版本">
              {{ host.kernel_version || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="监控状态">
              <el-switch 
                v-model="host.monitor_enabled" 
                @change="toggleMonitoring"
                active-text="已启用"
                inactive-text="已禁用"
              />
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatTime(host.created_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatTime(host.updated_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">
              {{ host.description || '无描述' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>硬件配置</span>
          </template>
          
          <div class="spec-item">
            <div class="spec-label">CPU核数</div>
            <div class="spec-value">{{ host.cpu_cores }} 核</div>
          </div>
          <div class="spec-item">
            <div class="spec-label">内存大小</div>
            <div class="spec-value">{{ host.memory_gb }} GB</div>
          </div>
          <div class="spec-item">
            <div class="spec-label">磁盘大小</div>
            <div class="spec-value">{{ host.disk_gb }} GB</div>
          </div>
          
          <el-divider />
          
          <div class="spec-item">
            <div class="spec-label">SSH端口</div>
            <div class="spec-value">{{ host.ssh_port }}</div>
          </div>
          <div class="spec-item">
            <div class="spec-label">SSH用户</div>
            <div class="spec-value">{{ host.ssh_username }}</div>
          </div>
          <div class="spec-item">
            <div class="spec-label">认证方式</div>
            <div class="spec-value">
              <el-tag size="small">
                {{ host.ssh_auth_type === 'password' ? '密码认证' : '密钥认证' }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时监控 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>实时监控</span>
              <el-switch
                v-model="autoRefresh"
                active-text="自动刷新"
                @change="toggleAutoRefresh"
              />
            </div>
          </template>
          
          <div v-if="metrics" class="metrics-grid">
            <div class="metric-card">
              <div class="metric-header">
                <el-icon><Cpu /></el-icon>
                <span>CPU使用率</span>
              </div>
              <div class="metric-content">
                <div class="metric-value">{{ metrics.cpu_usage.toFixed(1) }}%</div>
                <el-progress 
                  :percentage="metrics.cpu_usage" 
                  :color="getProgressColor(metrics.cpu_usage)"
                />
              </div>
            </div>
            
            <div class="metric-card">
              <div class="metric-header">
                <el-icon><MemoryStick /></el-icon>
                <span>内存使用率</span>
              </div>
              <div class="metric-content">
                <div class="metric-value">{{ metrics.memory_usage.toFixed(1) }}%</div>
                <el-progress 
                  :percentage="metrics.memory_usage" 
                  :color="getProgressColor(metrics.memory_usage)"
                />
              </div>
            </div>
            
            <div class="metric-card">
              <div class="metric-header">
                <el-icon><HardDrive /></el-icon>
                <span>磁盘使用率</span>
              </div>
              <div class="metric-content">
                <div class="metric-value">{{ metrics.disk_usage.toFixed(1) }}%</div>
                <el-progress 
                  :percentage="metrics.disk_usage" 
                  :color="getProgressColor(metrics.disk_usage)"
                />
              </div>
            </div>
            
            <div class="metric-card">
              <div class="metric-header">
                <el-icon><Loading /></el-icon>
                <span>系统负载</span>
              </div>
              <div class="metric-content">
                <div class="load-values">
                  <span>1m: {{ metrics.cpu_load_1m.toFixed(2) }}</span>
                  <span>5m: {{ metrics.cpu_load_5m.toFixed(2) }}</span>
                  <span>15m: {{ metrics.cpu_load_15m.toFixed(2) }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="no-metrics">
            <el-empty description="暂无监控数据" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 历史趋势图表 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>历史趋势</span>
              <el-radio-group v-model="selectedTimeRange" @change="fetchChartData">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
                <el-radio-button label="7d">7天</el-radio-button>
                <el-radio-button label="30d">30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          
          <div ref="chartContainer" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- SSH终端对话框 -->
    <el-dialog
      v-model="showSSHDialog"
      title="SSH终端"
      width="90%"
      :close-on-click-modal="false"
      custom-class="ssh-dialog"
    >
      <SSHTerminal :host-id="host.id" :auto-connect="true" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Monitor, Connection, Edit, Cpu, MemoryStick, HardDrive, Loading,
  CircleCheckFilled, CircleCloseFilled, Clock, WarningFilled
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import SSHTerminal from '@/components/ssh/SSHTerminal.vue'
import api from '@/utils/api'

// Props
interface Props {
  host: any
}

const props = defineProps<Props>()

// 响应式数据
const metrics = ref(null)
const autoRefresh = ref(true)
const selectedTimeRange = ref('1h')
const showSSHDialog = ref(false)
const chartContainer = ref<HTMLElement>()
let chart: echarts.ECharts | null = null
let refreshInterval: number | null = null

// 获取实时监控数据
const fetchMetrics = async () => {
  try {
    const response = await api.get('/monitoring/metrics/realtime/')
    if (response.data.success) {
      const hostMetrics = response.data.data.find(m => m.host === props.host.id)
      metrics.value = hostMetrics
    }
  } catch (error) {
    console.error('获取监控数据失败:', error)
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    const response = await api.post('/monitoring/metrics/stats/', {
      host_id: props.host.id,
      time_range: selectedTimeRange.value,
      metrics: ['cpu_usage', 'memory_usage', 'disk_usage']
    })
    
    if (response.data.success) {
      updateChart(response.data.data)
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 更新图表
const updateChart = (data: any) => {
  if (!chart) return
  
  const times = data.data.map(item => new Date(item.timestamp).toLocaleTimeString())
  const cpuData = data.data.map(item => item.cpu_usage)
  const memoryData = data.data.map(item => item.memory_usage)
  const diskData = data.data.map(item => item.disk_usage)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['CPU使用率', '内存使用率', '磁盘使用率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: times
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: 'CPU使用率',
        type: 'line',
        smooth: true,
        data: cpuData,
        lineStyle: { color: '#409EFF' },
        areaStyle: { opacity: 0.3 }
      },
      {
        name: '内存使用率',
        type: 'line',
        smooth: true,
        data: memoryData,
        lineStyle: { color: '#67C23A' },
        areaStyle: { opacity: 0.3 }
      },
      {
        name: '磁盘使用率',
        type: 'line',
        smooth: true,
        data: diskData,
        lineStyle: { color: '#E6A23C' },
        areaStyle: { opacity: 0.3 }
      }
    ]
  }
  
  chart.setOption(option)
}

// 初始化图表
const initChart = async () => {
  await nextTick()
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value)
    fetchChartData()
  }
}

// 工具函数
const getStatusType = (status: string) => {
  const typeMap = {
    'online': 'success',
    'offline': 'danger',
    'maintenance': 'warning',
    'error': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusIcon = (status: string) => {
  const iconMap = {
    'online': 'CircleCheckFilled',
    'offline': 'CircleCloseFilled',
    'maintenance': 'Clock',
    'error': 'WarningFilled'
  }
  return iconMap[status] || 'Monitor'
}

const getStatusText = (status: string) => {
  const textMap = {
    'online': '在线',
    'offline': '离线',
    'maintenance': '维护',
    'error': '故障'
  }
  return textMap[status] || '未知'
}

const getProgressColor = (value: number) => {
  if (value >= 90) return '#F56C6C'
  if (value >= 70) return '#E6A23C'
  return '#67C23A'
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

// 事件处理
const connectSSH = () => {
  showSSHDialog.value = true
}

const testConnection = async () => {
  try {
    ElMessage.info('正在测试连接...')
    const response = await api.post(`/cmdb/hosts/${props.host.id}/test_connection/`)
    if (response.data.success) {
      ElMessage.success('连接测试已启动')
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败')
  }
}

const handleEdit = () => {
  ElMessage.info('编辑功能开发中')
}

const toggleMonitoring = async (enabled: boolean) => {
  try {
    const response = await api.post(`/cmdb/hosts/${props.host.id}/toggle_monitoring/`, {
      enabled
    })
    if (response.data.success) {
      ElMessage.success(response.data.data.message)
    }
  } catch (error) {
    console.error('切换监控状态失败:', error)
    ElMessage.error('切换监控状态失败')
  }
}

const toggleAutoRefresh = (enabled: boolean) => {
  if (enabled) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

const startAutoRefresh = () => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
  refreshInterval = setInterval(() => {
    fetchMetrics()
  }, 10000) // 10秒刷新一次
}

const stopAutoRefresh = () => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
}

// 生命周期
onMounted(() => {
  fetchMetrics()
  initChart()
  
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

onUnmounted(() => {
  stopAutoRefresh()
  if (chart) {
    chart.dispose()
  }
})
</script>

<style scoped>
.host-detail {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.spec-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.spec-label {
  font-weight: 500;
  color: #606266;
}

.spec-value {
  color: #303133;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.metric-card {
  padding: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  background: #FAFAFA;
}

.metric-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  font-weight: 500;
  color: #606266;
}

.metric-content {
  text-align: center;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.load-values {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #606266;
}

.no-metrics {
  text-align: center;
  padding: 40px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

:deep(.ssh-dialog) {
  .el-dialog__body {
    padding: 0;
    height: 70vh;
  }
}
</style>
